<?php

/**
 * Name: 当班班长记录模型层
 * User: Silent
 * Date: 2025-11-07
 * Time: 15:00:00
 */

namespace App\Models\Checkin;

use App\Models\Config\Employee;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class DutyLeader extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'duty_leaders';

    protected $guarded = [];

    protected $casts = [
        'duty_date' => 'date:Y-m-d',
        'is_notified' => 'boolean',
        'notified_at' => 'datetime:Y-m-d H:i:s',
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s',
    ];

    protected static $logName = 'duty_leaders';

    protected function serializeDate(DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 关联班长（员工）
     */
    public function leader()
    {
        return $this->belongsTo(Employee::class, 'leader_id');
    }

    /**
     * 关联排班日志
     */
    public function logs()
    {
        return $this->hasMany(DutyLeaderLog::class, 'duty_leaders_id', 'id');
    }

    /**
     * 检查是否已通知
     */
    public function isNotified()
    {
        return $this->is_notified;
    }

    /**
     * 标记为已通知
     */
    public function markAsNotified()
    {
        $this->update([
            'is_notified' => true,
            'notified_at' => now()
        ]);
    }

    /**
     * 获取当天的当班班长
     */
    public static function getTodayDutyLeaders()
    {
        return self::where('duty_date', today())
                  ->with('leader')
                  ->get();
    }

    /**
     * 获取指定日期的当班班长
     */
    public static function getDutyLeadersByDate($date)
    {
        return self::where('duty_date', $date)
                  ->with('leader')
                  ->get();
    }
}

